package soccerscope.daistatistic;

import java.awt.BorderLayout;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.FlowLayout;
import java.awt.GraphicsEnvironment;
import java.awt.Panel;
import java.awt.Toolkit;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JProgressBar;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

import robocup.component.RobocupAgent;
import soccerscope.SoccerScopeMenuBar;
import soccerscope.model.ClientScene;
import soccerscope.model.WorldModel;

/**
 * 
 * implements the dialog for the player data
 */
public class PlayerDataDialog
    implements WindowListener {

  /**
   * 
   */
  private static final long   serialVersionUID     = 3617858564509544504L;

  private static int          dialogWidth          = 300;                 // dialog
                                                                          // dimensions

  private static int          dialogHigh           = 300;

  private static Dialog       dialog;                                     // reference
                                                                          // to a
                                                                          // Dialog

  private static JTable       table;                                      // reference
                                                                          // a
                                                                          // new
                                                                          // JTable

  private static MyTableModel model;                                      // reference
                                                                          // a
                                                                          // new
                                                                          // Table
                                                                          // Model

  private static JProgressBar staminaProgressBar;                         // reference
                                                                          // two
                                                                          // progress

  // bars

  private static JProgressBar speedProgressBar;

  protected static int        selectedPlayerNumber = 1;                   // show
                                                                          // data
                                                                          // of
                                                                          // the
                                                                          // player

  // with that number

  private static boolean      beep                 = false;

  Choice                      select1;                                    // reference
                                                                          // a
                                                                          // now
                                                                          // drop
                                                                          // down
                                                                          // menu

  /**
   * @author Andr�
   * 
   * this class defines the Player Data Dialog
   */
  public PlayerDataDialog(
      SoccerScopeMenuBar bar,
      soccerscope.SoccerScope frame,
      int yPixelMore) {

    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    int x = frame.getX() + frame.getWidth();
    while (x > (ge.getMaximumWindowBounds().width - PlayerDataDialog.dialogWidth)) {
      x--;
    }
    PlayerDataDialog.dialog = new Dialog(frame, "Player Data"); // create a new
                                                                // dialog with
    // our scope as "parent"
    PlayerDataDialog.dialog.setLayout(new FlowLayout(FlowLayout.CENTER));

    PlayerDataDialog.dialog.setSize(PlayerDataDialog.dialogWidth,
        PlayerDataDialog.dialogHigh); // set size
    PlayerDataDialog.dialog.setLocation(x, frame.getY() + yPixelMore);
    PlayerDataDialog.dialog.addWindowListener(this);
    PlayerDataDialog.dialog.setBackground(Color.LIGHT_GRAY);
    PlayerDataDialog.dialog.setVisible(false);

    // fill the drop down menu
    this.select1 = new Choice();
    this.select1.addItemListener(new MyItemListener());
    this.select1.addItem("Player 1");
    this.select1.addItem("Player 2");
    this.select1.addItem("Player 3");
    this.select1.addItem("Player 4");
    this.select1.addItem("Player 5");
    this.select1.addItem("Player 6");
    this.select1.addItem("Player 7");
    this.select1.addItem("Player 8");
    this.select1.addItem("Player 9");
    this.select1.addItem("Player 10");
    this.select1.addItem("Player 11");

    PlayerDataDialog.dialog.add(this.select1);

    // create the model which contains the data for the table
    PlayerDataDialog.model = new MyTableModel();

    // create the table
    PlayerDataDialog.table = new JTable();
    PlayerDataDialog.table.setRowSelectionAllowed(false);
    PlayerDataDialog.table.setColumnSelectionAllowed(false);
    PlayerDataDialog.table.setModel(PlayerDataDialog.model);
    PlayerDataDialog.dialog.add(PlayerDataDialog.table);

    // create the progress bars

    Panel progressPanel = new Panel();
    progressPanel.setLayout(new BorderLayout());
    PlayerDataDialog.staminaProgressBar = new JProgressBar(0, 4000);
    PlayerDataDialog.staminaProgressBar.setBackground(Color.BLACK);
    PlayerDataDialog.staminaProgressBar.setForeground(Color.BLUE);
    PlayerDataDialog.staminaProgressBar.setPreferredSize(new Dimension(90, 20));
    PlayerDataDialog.staminaProgressBar.setStringPainted(true);
    PlayerDataDialog.staminaProgressBar.setString("Stamina");
    progressPanel.add("West", PlayerDataDialog.staminaProgressBar);

    PlayerDataDialog.speedProgressBar = new JProgressBar(0, 120);
    PlayerDataDialog.speedProgressBar.setBackground(Color.BLACK);
    PlayerDataDialog.speedProgressBar.setForeground(Color.BLUE);
    PlayerDataDialog.speedProgressBar.setPreferredSize(new Dimension(90, 20));
    PlayerDataDialog.speedProgressBar.setStringPainted(true);
    PlayerDataDialog.speedProgressBar.setString("Speed");
    progressPanel.add("East", PlayerDataDialog.speedProgressBar);

    progressPanel.setPreferredSize(new Dimension(200, 20));
    PlayerDataDialog.dialog.add(progressPanel);

    PlayerDataDialog.setPlayer(1);

    // start thread for refill the table
    Controll controll = new Controll();
    Thread th = new Thread(controll);
    th.start();
  }

  /**
   * 
   * returns true if the dialog is visible else false
   * 
   * @return boolean
   */
  public boolean dialogVisible() {

    return PlayerDataDialog.dialog.isVisible();
  }

  /**
   * 
   * set visible or not
   * 
   * @param boolean
   */
  public static void setVisible(boolean mode) {

    PlayerDataDialog.dialog.setVisible(mode);
  }

  /**
   * 
   * set to a new player, also the actual player in action dialog will set to
   * that player
   * 
   * @param int
   *          playerNumber, the new player
   */
  public static void setPlayer(int playerNumber) {

    PlayerDataDialog.selectedPlayerNumber = playerNumber;
    RobocupAgent player = null; // RobocupAgent.createAgent(new
    // Properties());
    if (playerNumber > 0 && playerNumber < 12) {
      if (ActionDialog.getDialog() != null) {
        ActionDialog.actualPlayerNumber = playerNumber;
        ActionDialog.setTitle("Action Dialog for Player " + playerNumber);
        ActionDialog.buttonsOff();
      }
      player = Register.getPlayerBeanWithPlayerNumber(playerNumber);
    }
    if (player != null) {
      PlayerDataDialog.fillTable(player);
    }
  }

  /**
   * 
   * fills the table model with actual data and repaint the table
   * 
   * @param PlayerBean
   *          player the player
   */
  public static void fillTable(RobocupAgent player) {

    if (player == null) {
      if (!PlayerDataDialog.beep) {
        Toolkit.getDefaultToolkit().beep();
      }
      PlayerDataDialog.beep = true;
      return;
    }
    PlayerDataDialog.beep = false;
    PlayerDataDialog.model.setBallPosition(player.getWorld().getBallRef()
        .getPosition().x, player.getWorld().getBallRef().getPosition().y);
    PlayerDataDialog.model.setPos(
        player.getWorld().getSelfRef().getPosition().x, player.getWorld()
            .getSelfRef().getPosition().y);
    PlayerDataDialog.model.setSpeedXY(
        player.getWorld().getSelfRef().getSpeed().x, player.getWorld()
            .getSelfRef().getSpeed().y);
    PlayerDataDialog.model.setStamina(player.getWorld().getSelfRef()
        .getStamina());
    PlayerDataDialog.model.setAngles(player.getWorld().getViewWidth(), player
        .getWorld().getSelfRef().getNeckAngle(), player.getWorld()
        .getBodyAngle());

    ClientScene scene = WorldModel.sceneSet.lastScene();
    PlayerDataDialog.model.setCoachPos(scene.player[player.getWorld()
        .getNumber() - 1].pos.y,
        scene.player[player.getWorld().getNumber() - 1].pos.x);
    PlayerDataDialog.model.setCoachBallPosition(scene.ball.pos.y,
        scene.ball.pos.x);

    PlayerDataDialog.table.repaint();

  }

  /**
   * 
   * repaint the table
   */
  public static void tableRepaint() {

    PlayerDataDialog.fillTable(Register
        .getPlayerBeanWithPlayerNumber(PlayerDataDialog.selectedPlayerNumber));
    PlayerDataDialog.table.repaint();
  }

  /**
   * 
   * set the value for the stamina progress bar
   * 
   * @param int
   *          value
   */
  public static void setStaminaProgressBarValue(int value) {

    PlayerDataDialog.staminaProgressBar.setValue(value);
  }

  /**
   * 
   * set the value for the speed progress bar
   * 
   * @param double
   *          value
   */
  public static void setSpeedProgressBarValue(double value) {

    String help = Double.toString(value);
    if (help.indexOf(".") > 0) {
      help = help.substring(0, help.indexOf("."));
    }
    PlayerDataDialog.speedProgressBar.setValue(Integer.parseInt(help));
  }

  /**
   * 
   * getter for the dialog
   */
  public static Dialog getDialog() {

    return PlayerDataDialog.dialog;
  }

  public void windowOpened(WindowEvent arg0) {

  }

  public void windowClosing(WindowEvent arg0) {

    PlayerDataDialog.dialog.setVisible(false);
  }

  public void windowClosed(WindowEvent arg0) {

  }

  public void windowIconified(WindowEvent arg0) {

  }

  public void windowDeiconified(WindowEvent arg0) {

  }

  public void windowActivated(WindowEvent arg0) {

  }

  public void windowDeactivated(WindowEvent arg0) {

  }

}

/**
 * 
 * the item listener for the pull down menu
 */
class MyItemListener
    implements ItemListener {

  /*
   * (non-Javadoc)
   * 
   * @see java.awt.event.ItemListener#itemStateChanged(java.awt.event.ItemEvent)
   */
  public void itemStateChanged(ItemEvent arg0) {

    Choice target = (Choice) arg0.getSource();

    if (arg0.getID() == Event.LIST_SELECT || arg0.getID() == Event.LIST_DESELECT || arg0
        .getID() == Event.SCROLL_END) {

      if (target.getSelectedItem().equals("Player 1")) {
        PlayerDataDialog.setPlayer(1);
      }
      if (target.getSelectedItem().equals("Player 2")) {
        PlayerDataDialog.setPlayer(2);
      }
      if (target.getSelectedItem().equals("Player 3")) {
        PlayerDataDialog.setPlayer(3);
      }
      if (target.getSelectedItem().equals("Player 4")) {
        PlayerDataDialog.setPlayer(4);
      }
      if (target.getSelectedItem().equals("Player 5")) {
        PlayerDataDialog.setPlayer(5);
      }
      if (target.getSelectedItem().equals("Player 6")) {
        PlayerDataDialog.setPlayer(6);
      }
      if (target.getSelectedItem().equals("Player 7")) {
        PlayerDataDialog.setPlayer(7);
      }
      if (target.getSelectedItem().equals("Player 8")) {
        PlayerDataDialog.setPlayer(8);
      }
      if (target.getSelectedItem().equals("Player 9")) {
        PlayerDataDialog.setPlayer(9);
      }
      if (target.getSelectedItem().equals("Player 10")) {
        PlayerDataDialog.setPlayer(10);
      }
      if (target.getSelectedItem().equals("Player 11")) {
        PlayerDataDialog.setPlayer(11);
      }
    }
  }
}

/**
 * 
 * the TableModel
 */
class MyTableModel
    extends AbstractTableModel {

  /**
   * 
   */
  private static final long serialVersionUID = 3905805279462373683L;

  // Player Values
  String                    xPos             = "0";

  String                    yPos             = "0";

  String                    stamina          = "3000";

  String                    speed            = "0.0";

  String                    speedX           = "0.0";

  String                    speedY           = "0.0";

  String                    viewQuality      = "1";

  String                    viewAngle        = "90";

  String                    neckAngle        = "0";

  String                    bodyAngle        = "0";

  String                    ballPosition     = "(0,0)";

  String                    holes            = "0";

  String                    actions          = "0";

  String                    noActions        = "0";

  // Coach Values
  String                    cxPos            = "0";

  String                    cyPos            = "0";

  String                    cballPosition    = "(0,0)";

  public int getRowCount() {

    return 12;
  }

  public int getColumnCount() {

    return 3;
  }

  /**
   * 
   * get the object of a spezified position
   * 
   * @param int
   *          row
   * @param int
   *          col
   */
  public Object getValueAt(int row,
      int col) {

    if (col == 0) {
      if (row == 0) {
        return " Position X";
      }
      if (row == 1) {
        return " Position Y";
      }
      if (row == 2) {
        return " Stamina";
      }
      if (row == 3) {
        return " Speed";
      }
      if (row == 4) {
        return " View Quality";
      }
      if (row == 5) {
        return " View Angle";
      }
      if (row == 6) {
        return " Neck Angle";
      }
      if (row == 7) {
        return " Body Angle";
      }
      if (row == 8) {
        return " Ball Position";
      }
      if (row == 9) {
        return " Holes";
      }
      if (row == 10) {
        return " Actions";
      }
      if (row == 11) {
        return " No Actions";
      }
    }

    if (col == 1) {
      if (row == 0) {
        return this.xPos;
      }
      if (row == 1) {
        return this.yPos;
      }
      if (row == 2) {

        PlayerDataDialog.setStaminaProgressBarValue(Integer
            .parseInt(this.stamina));
        return this.stamina;
      }
      if (row == 3) {
        this.speed = Double
            .toString(java.lang.Math
                .sqrt(Double.parseDouble(this.speedX) * Double
                    .parseDouble(this.speedX) + Double.parseDouble(this.speedY) * Double
                    .parseDouble(this.speedY)));
        PlayerDataDialog.setSpeedProgressBarValue(Double
            .parseDouble(this.speed) * 100);
        return "(" + this.speedX + "," + this.speedY + ")";
      }
      if (row == 4) {
        return this.viewQuality;
      }
      if (row == 5) {
        return this.viewAngle;
      }
      if (row == 6) {
        return this.neckAngle;
      }
      if (row == 7) {
        return this.bodyAngle;
      }
      if (row == 8) {
        return this.ballPosition;
      }
      if (row == 9) {
        return this.holes;
      }
      if (row == 10) {
        return this.actions;
      }
      if (row == 11) {
        return this.noActions;
      }
    }
    if (col == 2) {
      if (row == 0) {
        return this.cxPos;
      }
      if (row == 1) {
        return this.cyPos;
      }
      if (row == 8) {
        return this.cballPosition;
      }
    }

    return "";
  }

  /**
   * 
   * set the absolute (coach view) position
   * 
   * @param double
   *          x
   * @param double
   *          y
   */
  public void setCoachPos(double x,
      double y) {

    this.cxPos = Double.toString(x);
    this.cyPos = Double.toString(y);
    if (this.cxPos.length() > 5) {
      this.cxPos = this.cxPos.substring(0, 5);
    }
    if (this.cyPos.length() > 5) {
      this.cyPos = this.cyPos.substring(0, 5);
    }
  }

  /**
   * 
   * set the absolute (coach view) ball position
   * 
   * @param double
   *          x
   * @param double
   *          y
   */
  public void setCoachBallPosition(double x,
      double y) {

    String helpX = Double.toString(x);
    String helpY = Double.toString(y);
    if (helpX.length() > 5) {
      helpX = helpX.substring(0, 5);
    }
    if (helpY.length() > 5) {
      helpY = helpY.substring(0, 5);
    }
    this.cballPosition = "(" + helpX + "," + helpY + ")";
  }

  /**
   * 
   * set the position
   * 
   * @param double
   *          x
   * @param double
   *          y
   */
  public void setPos(double x,
      double y) {

    this.xPos = Double.toString(x);
    this.yPos = Double.toString(y);
    if (this.xPos.length() > 5) {
      this.xPos = this.xPos.substring(0, 5);
    }
    if (this.yPos.length() > 5) {
      this.yPos = this.yPos.substring(0, 5);
      // System.out.println("XPos: " + xPos + " YPos: " + yPos);
    }
  }

  /**
   * 
   * set the stamina
   * 
   * @param double
   *          stam
   */
  public void setStamina(double stam) {

    String help = Double.toString(stam);
    if (help.indexOf(".") > 0) {
      help = help.substring(0, help.indexOf("."));
    }
    this.stamina = help.toString();
  }

  /**
   * 
   * set the speed
   * 
   * @param double
   *          sp
   */
  public void setSpeed(double sp) {

    this.speed = Double.toString(sp);
  }

  /**
   * 
   * set the speed with x and y direction
   * 
   * @param double
   *          x
   * @param double
   *          y
   */
  public void setSpeedXY(double x,
      double y) {

    this.speedX = Double.toString(x);
    this.speedY = Double.toString(y);
    if (this.speedX.length() > 5) {
      this.speedX = this.speedX.substring(0, 5);
    }
    if (this.speedY.length() > 5) {
      this.speedY = this.speedY.substring(0, 5);
    }
  }

  /**
   * 
   * set the view quality
   * 
   * @param double
   *          qual
   */
  public void setViewQuality(double qual) {

    this.viewQuality = Double.toString(qual);
  }

  /**
   * 
   * set the player angles
   * 
   * @param double
   *          view
   * @param double
   *          neck
   * @param double
   *          body
   */
  public void setAngles(double view,
      double neck,
      double body) {

    this.viewAngle = Double.toString(view);
    if (this.viewAngle.length() > 5) {
      this.viewAngle = this.viewAngle.substring(0, 5);
    }
    this.neckAngle = Double.toString(neck);
    if (this.neckAngle.length() > 5) {
      this.neckAngle = this.neckAngle.substring(0, 5);
    }
    this.bodyAngle = Double.toString(body);
    if (this.bodyAngle.length() > 5) {
      this.bodyAngle = this.bodyAngle.substring(0, 5);
    }
  }

  /**
   * 
   * set the ball position
   * 
   * @param double
   *          x
   * @param double
   *          y
   */
  public void setBallPosition(double x,
      double y) {

    String helpX = Double.toString(x);
    String helpY = Double.toString(y);
    if (helpX.length() > 5) {
      helpX = helpX.substring(0, 5);
    }
    if (helpY.length() > 5) {
      helpY = helpY.substring(0, 5);
    }
    this.ballPosition = "(" + helpX + "," + helpY + ")";
  }

  /**
   * 
   * set the holes
   * 
   * @param int
   *          h
   */
  public void setHoles(int h) {

    this.holes = Double.toString(h);
  }

  /**
   * 
   * set the executed actions
   * 
   * @param double
   *          a
   */
  public void setActions(double a) {

    this.actions = Double.toString(a);
  }

  /**
   * 
   * set the actions without holes
   * 
   * @param double
   *          awh
   */
  public void setActionsWithoutHoles(double awh) {

    this.noActions = Double.toString(awh);
  }

}

class Controll
    implements Runnable {

  /*
   * (non-Javadoc)
   * 
   * @see java.lang.Runnable#run()
   */
  int          cycle  = 0;

  RobocupAgent player = null;

  public void run() {

    this.player = Register.getPlayerBeanWithPlayerNumber(1);
    if (this.player != null) {
      this.cycle = this.player.getWorld().getCycle();
      while (true) {
        if (this.player.getWorld().getCycle() != this.cycle) {
          PlayerDataDialog.tableRepaint();
          this.cycle++;
        }
        try {
          Thread.sleep(80);

        }
        catch (Exception e) {
        }
      }
    }
  }
}
/**
 * $Log: PlayerDataDialog.java,v $ Revision 1.3 2006/11/06 17:05:26 wetzker
 * added docu to and simplified wm
 * 
 * Revision 1.2 2006/11/05 13:58:04 wetzker more merging - CLang + MF + some
 * states still missing
 * 
 * Revision 1.1.28.2 2006/07/31 13:36:30 endert Added Java-Doc to constructors
 * if missing, minor refactorings. Revision 1.1.28.1 2006/07/26 15:28:36 endert
 * Formatted Code Revision 1.1 2006/03/13 07:38:28 axle moved from ROOT/src for
 * Maven 2 Buildsystem and Team/Soccerscope separation
 * 
 * Revision 1.13 2006/03/07 12:46:17 endert Merge after refactoring: - New
 * State-Interface: One Method for each action type - Action Bean removed -
 * ActionFactorys for helper methods, States calculate main-Action themselves -
 * formatted code - added State-List in Monitor (Context-Menu of Player) - other
 * smaller stuff
 * 
 * Revision 1.12.2.1 2006/02/25 22:07:28 wetzker formated
 * 
 * Revision 1.12 2006/02/22 16:05:09 endert This is done: - Rebound SoccerScope
 * to Agents (can be added or removed in config-file) - Situations now all
 * extend abstract class Situation - Refactorings: ActionBean _ removed from
 * Attributes - SoccerScope will automatically connect to host given in
 * Start-Call - Trainer uses the same host as soccerscope - Removed unused stuff
 * (old confs, bat, etc.) - Code formatted (good luck when merging) - organized
 * imports - all that i forgot to mention here Revision 1.11 2005/08/16 16:26:37
 * wetzker merged composite branch
 * 
 * Revision 1.10.4.1 2005/08/16 15:43:29 wetzker removed ball and player cloning
 * in getSelf, getBall -> should be much faster now merged with changes from
 * head
 * 
 * Revision 1.10 2005/06/20 17:30:39 andpaul documentation
 * 
 * Revision 1.9 2005/06/16 12:56:09 endert Improved RobocupAgent initialisation:
 * Connection to the server should now always be successful. Therefor, the
 * Agents Constructor is made private and the method RobocupAgent.createAgent()
 * handles creation, connection and starting of the agents thread.
 * 
 * Revision 1.8 2005/06/15 17:03:31 wetzker removed JIAC from Head + changes in
 * framework please report bugs or shortcomings some scenarios might not work
 * because of wrong imports
 * 
 * Revision 1.7.2.1 2005/06/09 12:32:07 endert Removal of JIAC Libraries and
 * dependencies from project, restructuring the framework and improve some
 * aspects (hoping it is an improvement)
 * 
 * Revision 1.7 2005/05/13 22:20:56 wetzker refactoring in LongTermMemory
 * renamed some strange methods gui-statistic is not updated with constant cycle
 * as everything jumps when PM changes turned off some (strange looking)
 * if-cases in GUI-Statistics MeModel now contains viewWidth and viewQuality
 * 
 * Revision 1.6 2005/05/11 12:11:06 andpaul added: beep when player not
 * available
 * 
 * Revision 1.5 2005/05/11 10:08:10 andpaul fix: null pointer exception if no
 * player is connected
 * 
 * Revision 1.4 2005/05/11 09:57:29 andpaul changed: window handling with soccer
 * scope added: layout manager to PlayerDataDialog and ActionDialog fix: some
 * "null pointers" when an unknown player was selected
 * 
 * Revision 1.3 2005/05/05 10:09:19 haeder - removed unused import
 * 
 * Revision 1.2 2005/04/25 14:53:40 andpaul changed coach to monitor data
 * 
 * Revision 1.1 2005/04/20 10:39:38 endert Fresh Team Repository installation
 * from /home/e/endert/Robocup to here.
 * 
 * Revision 1.6 2005/04/02 11:08:04 andpaul documentation
 * 
 * Revision 1.5 2005/03/29 12:41:48 andpaul changes for the new MyWindowListener
 * 
 * Revision 1.4 2005/03/13 14:58:18 haeder replaced Dialog.show() by
 * Component.setVisible() because it is deprecated
 * 
 * Revision 1.3 2005/02/12 22:54:10 andpaul check if a coach and visual info is
 * available
 * 
 * Revision 1.2 2005/02/06 20:04:17 andpaul documentation, nothing else
 * 
 * Revision 1.1 2005/02/06 17:13:36 andpaul setting up old gui functions for the
 * new gui
 * 
 * Revision 1.3 2005/01/30 16:20:21 andpaul added player select drop down menu
 * 
 * Revision 1.2 2005/01/30 15:11:15 andpaul added tablemodel and table value
 * setter
 * 
 * Revision 1.1 2005/01/29 21:35:31 andpaul better dialog location handling
 * 
 * Revision 1.0 2005/01/29 20:43:31 andpaul first steps to the "on the fly" WM
 * Data viewer
 * 
 * 
 */
